import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from "axios";
import store from "../store"

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: "LoginInfo",
    component: () => import('../views/Login.vue'),
    redirect: "/login",
    children: [
      {path: '/login', name: "Login",
        meta:{
          title: '学生信息管理系统',
        }, component: () => import('../views/Login.vue')},
    ]
  },
  {
    path: '/manage',
    name:"Manage",
    component: () => import('../views/Manage.vue'),
    redirect: "/home",
    children: [
      {path: '/home', name: "Home",
        meta:{title: '首页',},component: () => import('../views/Home.vue')},
      {path: '/person', name: "Person",
        meta:{title: '个人信息',},component: () => import('../views/Person.vue')},
      {path: '/change', name: "Change",
        meta:{title: '修改密码',},component: () => import('../views/Change.vue')},
    ]
  },


]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }

  let hasRoute = store.state.menus.hasRoutes
  let token = localStorage.getItem("token")

  if (to.path === '/login') {
    next()
  } else if (!token) {
    next({path: '/login'})
  } else if(token && !hasRoute) {
    axios.get("/sys/menu/nav",{
      headers: {
        Authorization: localStorage.getItem("token")
      }
    }).then(res => {
      console.log(res.data.data)
      // 拿到menuList
      store.commit("setMenuList",res.data.data.nav)
      // 拿到用户权限
      store.commit("setPermList",res.data.data.authoritys)
      console.log(store.state.menus.menuList)
      //动态绑定路由
      let newRoutes = router.options.routes
      res.data.data.nav.forEach(menu => {
        if (menu.children){
          menu.children.forEach(e => {
            //转换成路由
            let route = menuToRoute(e)
            //把路由添加到路由管理器中
            if (route){
              newRoutes[1].children.push(route)
            }
          })
        }
      })
      newRoutes.forEach(newRouter => {
        router.addRoute(newRouter)
      })
      hasRoute = true
      store.commit("changeRouteStatus", hasRoute)
    })
  }
  next()
});

//导航转成路由
const menuToRoute = (menu) => {
  if (!menu.component){
    return null
  }
  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = () => import('../views/'+menu.component+'.vue')
  return route
}

export default router
